﻿using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using CoachingOrganizer.Android;
using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.Android.Mediators;
using CoachingOrganizer.Android.Adapters;
using CoachingOrganizer.Toolkit.Events;
using CoachingOrganizer.Android.Helpers;

namespace CoachingOrganizer.Android.Activities
{
    [Activity(Label = "@string/ApplicationName", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private readonly InteractionModel _model = ModelsMediator.Instance.Model;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.MainLayout);
            Init();
        }

        protected override void OnResume()
        {
            base.OnResume();
            HookModel();
        }

        protected override void OnPause()
        {
            base.OnPause();
            UnhookModel();
        }

        private async void Init()
        {
            using (System.Threading.CancellationTokenSource cancellation = new System.Threading.CancellationTokenSource())
                await _model.LoadPeriodsAsync(cancellation.Token);
        }

        private void HookModel()
        {
            _model.CurrentPeriodChanged += Model_CurrentPeriodChanged;
            Button addPeriodButton = FindViewById<Button>(Resource.Id.AddPeriodButton);
            addPeriodButton.Click += AddPeriodButton_Click;
            ListView periodsListView = FindViewById<ListView>(Resource.Id.periodsListView);
            periodsListView.Adapter = new PeriodsAdapter(this, _model);
        }

        private void UnhookModel()
        {
            _model.CurrentPeriodChanged -= Model_CurrentPeriodChanged;
            Button addPeriodButton = FindViewById<Button>(Resource.Id.AddPeriodButton);
            addPeriodButton.Click -= AddPeriodButton_Click;
            ListView periodsListView = FindViewById<ListView>(Resource.Id.periodsListView);
            if (periodsListView.Adapter != null)
                periodsListView.Adapter.Dispose();
        }

        private async void AddPeriodButton_Click(object sender, EventArgs e)
        {
            ActionResult addResult = await _model.AddNewPeriod();
            if (!addResult.IsValid)
                ;
        }

        private void Model_CurrentPeriodChanged(object sender, EventArgs e)
        {
            UIHelper.GoActivity<PeriodModel>(this, _model.CurrentPeriod, typeof(PeriodDetailsActivity));
        }
    }
}

